package com.lepu.app.usercenter;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.usercenter.util.UserCenterUtil;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class FeedBackActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		AsyncRequest,OnEditorActionListener {

	private String mAdviceID = "";
	private boolean mFlag = false;//防止发送按钮重复点击
	
	private int mMaxLength = 0;
	private boolean mCanSend = true;
	private TextView mCountTextView = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usercenter_feedback_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		
		if(getIntent() != null){
			mAdviceID = getIntent().getStringExtra("AdviceID");
		}
		
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("意见反馈");
		topbar.setRightText("提交");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);

		mCountTextView = (TextView) findViewById(R.id.countTextView);
		mMaxLength = 400;
		EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
		contentEditText.setFilters(new InputFilter[] { new EmojiFilter(),new InputFilter.LengthFilter(mMaxLength) });//400
		contentEditText.addTextChangedListener(mTextWatcher);
		
		EditText contactEditText = (EditText) findViewById(R.id.contactEditText);
		contactEditText.setOnEditorActionListener(this);
		contactEditText.setFilters(new InputFilter[] { new EmojiFilter(),new InputFilter.LengthFilter(11) });
		
		ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
		scrollView.setOnTouchListener(new OnTouchListener() {
			
			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(FeedBackActivity.this);
				return false;
			}
		});
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {

		send();
	}
	
	private void send()
	{
		if(mFlag)
		{
			return;
		}

		mFlag = true;

		boolean loginFlag = LoginUtil.jumpLogin(this);
		if (!loginFlag) {
			EditText contentEditText = (EditText) findViewById(R.id.contentEditText);
			EditText contactEditText = (EditText) findViewById(R.id.contactEditText);

			String content = contentEditText.getText().toString().trim();
			String contact = contactEditText.getText().toString().trim();
			
			if (!mCanSend) {
				UIHelper.showToast(this, String.format("请输入少于%d个字的问题", mMaxLength));
				return;
			}

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			boolean flag = UserCenterUtil.getFeedback(this, this, "",
					loginInfo.UserID, loginInfo.LoginToken, content, contact,mAdviceID);
			if (flag) {
				showProgressDialog(false);
			}
			mFlag = false;
		}
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:

				hideProgressDialog();

				MyDialog dialog = new MyDialog(FeedBackActivity.this)
						.setMessage("非常感谢您的建议，我们会及时去解决问题。")
						.setNegativeButtonSplitImageHide(true)
						.setPositiveButton(R.string.app_ok,
								new View.OnClickListener() {

									@Override
									public void onClick(View v) {

										finish(true);
										
										FeedBackMainActivity instance = (FeedBackMainActivity) AppManager.getAppManager().getActivity(FeedBackMainActivity.class);
										if(instance != null)
										{
											instance.mGoogleRefreshLayout.setRefreshing(true);
											instance.request(false);
										}
									}
								});
				dialog.create(null);
				dialog.setCancelable(false);
				dialog.setCanceledOnTouchOutside(false);
				dialog.showMyDialog();
				
				break;
			case 1:

				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};
	
	TextWatcher mTextWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
			int len = s.toString().length();

			if (len <= mMaxLength) {
				mCanSend = true;

				mCountTextView.setTextColor(getResources().getColor(
						R.color.color_text_black2));
			} else {
				mCanSend = false;

				mCountTextView.setTextColor(getResources().getColor(
						R.color.color_text_highlight));
			}
			mCountTextView.setText(String.format("(%d/%d)", len, mMaxLength));
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};

	@Override
	public void RequestComplete(Object object, Object data) {

		String result = (String) data;
		int code = 0;
		try {
			JSONObject jsonObject = new JSONObject(result);
			JSONObject obj1 = (JSONObject) jsonObject.get("Result");
			code = obj1.optInt("Status");
		} catch (JSONException e) {
			e.printStackTrace();
		}

		if (code == 200) {
			mHandler.sendEmptyMessage(0);
		} else {
			mHandler.sendEmptyMessage(1);
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		mHandler.sendEmptyMessage(1);
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEND:
			
			send();
			break;
		}
		return false;
	}
}
